import { useRequest } from 'ahooks';
import { Button, Empty, Form, Input, Spin, Typography } from 'antd';
import { useState } from 'react';
import { useTranslation } from 'react-i18next';

import { PrismCode } from '@/components/SourceCode';
import SourceCode from '@/components/SourceCode';
import { VulnerableProps } from '@/components/VulnerableTemplate/type';
import rceCode from '@/pages/vulnerable/code/rce';

import { ping } from '../../service';
const { Title } = Typography;

const codeProps: PrismCode = {
  language: 'tsx',
  code: rceCode.ping,
};

const Vulnerable: React.FC = () => {
  const { t } = useTranslation();
  const [form] = Form.useForm();
  const [shell, setShell] = useState('');

  const { run, loading } = useRequest(
    async () => {
      const ip = form.getFieldValue('ip');
      await ping(ip)
        .then(res => setShell(res.stdout))
        .catch(err => setShell(err.response.data.error));
    },
    { manual: true },
  );

  return (
    <>
      <Title italic level={4}>
        {t('rce.ping.title')}
      </Title>
      <Form form={form}>
        <Input.Group compact>
          <Form.Item name="ip" noStyle>
            <Input style={{ width: 200, marginBottom: 20 }} />
          </Form.Item>
          <Button onClick={run}>ping</Button>
        </Input.Group>
      </Form>
      <Title italic level={4}>
        {t('result')}
      </Title>
      <Spin spinning={loading}>
        {shell !== '' ? (
          <SourceCode
            className="border border-[#e5e7eb] overflow-scroll"
            language="bash"
            code={shell}
          />
        ) : (
          <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={t('empty')} />
        )}
      </Spin>
    </>
  );
};

const RcePing: VulnerableProps = {
  vulnerable: <Vulnerable />,
  codeProps,
  causesSolutions: {
    type: 'rce',
    hasCompare: true,
    solutions: 3,
  },
};

export default RcePing;
